import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {
  _HttpClient,
  ModalHelper,
  SettingsService,
  TitleService,
} from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { ActivatedRoute, Router } from '@angular/router';
import { of } from 'rxjs/index';
import { catchError } from 'rxjs/operators';
import { PopService } from '../../../../service/pop/pop.service';
import { EmitterService } from '../../../../service/emit.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { format } from 'date-fns';
import { CommService } from '../../../../service/comm/comm.service';

@Component({
  selector: 'pop-order-view',
  templateUrl: './view.component.html',
})
export class PopOrderViewComponent implements OnInit, OnDestroy {
  loading = false;
  sub: any;
  billId;
  order: [{ [proname: string]: any }] = [{}];
  // list: {[proname: string]: any}[] = [];
  totalQty = 0;
  totalExwPrice = 0;
  totalCifPrice = 0;
  imgSuffix = '';
  // 显示图片
  previewVisible = false;
  // 大图地址
  previewImage = '';
  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [
    { title: '图片', index: 'img', i18n: 'img', render: 'img', width: '100px' },
    { title: 'SKU', index: 'sku', i18n: 'sku_number' },
    { title: '描述', index: 'description', i18n: 'description' },
    { title: '净重', index: 'netWeight', i18n: 'net_weight' },
    { title: '毛重', index: 'grossWeight', i18n: 'gross_weight' },
    { title: '数量', index: 'qty', i18n: 'qty' },
    { title: 'EXW', index: 'exw' },
    { title: 'TOTAL EXW', index: 'totalExw' },
    { title: 'CIF', index: 'cif' },
    { title: 'TOTAL CIF', index: 'totalCif' },
  ];

  pzDate = null;
  jhDate = null;
  visible = false;

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private route: ActivatedRoute,
    private popService: PopService,
    private emit: EmitterService,
    private titleService: TitleService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private router: Router,
    private settings: SettingsService,
    private comm: CommService,
  ) {}

  ngOnInit() {
    this.imgSuffix = this.comm.getGoodsUrl();
    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.billId = params['billId'];
      this.info();
      // this.calcTotalPrice();
    });

    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage('HIDE_REUSE_TAB');
    }, 100);
    this.titleService.setTitle('订单明细');
  }

  ngOnDestroy() {
    this.emit.sendMessage('SHOW_REUSE_TAB');
  }

  info() {
    this.popService
      .detail(this.billId)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        if (data.status === 200) {
          this.order = data.data.rows;
          this.qtyCount();
          this.calcTotalPrice();
          // this.setOrderStep();
        } else {
          this.msg.error(data.message);
        }
      });
  }

  qtyCount() {
    this.totalQty = 0;
    for (let i = 0; i < this.order.length; i++) {
      this.totalQty += this.order[i].qty;
    }
  }

  calcTotalPrice() {
    this.totalExwPrice = 0;
    this.totalCifPrice = 0;
    for (let i = 0; i < this.order.length; i++) {
      this.totalExwPrice += this.order[i].totalExw;
      this.totalCifPrice += this.order[i].totalCif;
    }
  }

  back() {
    this.router.navigate(['/pop/order']);
  }

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  sure() {
    // 如果非管理账号, 直接提示并调用后台; 管理账号则弹窗输入一些参数
    if (this.settings.user.isManager) {
      this.open();
    } else {
      this.modalService.confirm({
        nzTitle: 'Are you sure?',
        nzContent: '<b style="color: red;">The order will be confirm</b>',
        nzOkText: 'Yes',
        nzOnOk: () => {
          this.loading = true;
          this.popService
            .sureOrder(this.billId)
            .pipe(
              catchError(err => {
                return of(err);
              }),
            )
            .subscribe(data => {
              this.loading = false;
              if (data.status === 200) {
                this.msg.success('Successful');
                this.info();
                this.emit.sendMessage('RELOAD_ORDERS_LIST');
              } else {
                this.msg.error(data.message);
              }
            });
        },
        nzCancelText: 'No',
        nzOnCancel: () => {},
      });
    }
  }

  cancelOrder() {
    this.modalService.confirm({
      nzTitle: 'Are you sure?',
      nzContent: '<b style="color: red;">The order will be cancel</b>',
      nzOkText: 'Yes',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.loading = true;
        this.popService
          .cancelOrder(this.billId)
          .pipe(
            catchError(err => {
              return of(err);
            }),
          )
          .subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
              this.msg.success('Successful');
              this.info();
              this.emit.sendMessage('RELOAD_ORDERS_LIST');
            } else {
              this.msg.error(data.message);
            }
          });
      },
      nzCancelText: 'No',
      nzOnCancel: () => {},
    });
  }

  open(): void {
    this.pzDate = null;
    this.jhDate = null;
    this.visible = true;
  }

  close(): void {
    this.visible = false;
  }

  submit(): void {
    if (!this.pzDate) {
      this.msg.warning('凭证日期不能空');
      return;
    }
    if (!this.jhDate) {
      this.msg.warning('交货日期不能空');
      return;
    }

    this.close();
    this.loading = true;
    this.popService
      .sureOrder(
        this.billId,
        format(this.pzDate, 'YYYYMMDD'),
        format(this.jhDate, 'YYYYMMDD'),
      )
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(data => {
        this.loading = false;
        if (data.status === 200) {
          this.msg.success('Successful');
          this.info();
          this.emit.sendMessage('RELOAD_ORDERS_LIST');
        } else {
          if (data.message) {
            this.msg.error(data.message);
            return;
          } else {
            this.msg.error(data.respMsg);
            return;
          }
        }
      });
  }
}
